var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
var bodyParser = require('body-parser');

var port = 7890;
const session = require('express-session');
const fileStore = require('session-file-store')(session);
const users = require('./users').users;

// 地图数据
var DUMPDATA = {};

// socket clients
var CLIENTS = [];

// 静态文件
app.use(express.static('static'));

//body-parser 解析json格式数据
app.use(bodyParser.json({
    limit: '1mb'
}));

app.set('views', './views');
app.set('view engine', 'ejs');

//此项必须在 bodyParser.json 下面,为参数编码
app.use(bodyParser.urlencoded({
    extended: true
}));

app.use(session({
    name: 'pubg',
    secret: 'pubg_map_assistant',
    store: new fileStore(),
    saveUninitialized: false,
    resave: false,
    cookie: {
        maxAge: 60*60*1000
    }
}))

app.get('/', function (req, res) {
    console.log(req.session.login, req.session.user);
    if (req.session.login) {
        res.render('home', {data: 'ok'});
    } else {
        res.redirect('/login');
    }
})

app.get('/login', function (req, res) {
    res.render('login/index', {foo: 'bar'});
})

app.post('/login', function (req, res) {
    let user = users.find(function (item) {
        return item.phone === req.body.phone && item.password === req.body.pass;
    });
    console.log(user);
    if (user) {
        req.session.regenerate(function (err) {
            if (err) console.log(err);
            req.session.user = user.phone;
            req.session.login = true;
            res.redirect('/')
        })
    } else {
        res.render('login/index', {data: '用户名或密码错误'});
    }
})

app.get('/ejs', function (req, res) {
    res.render('home', {data: 'foo'});
})
//  POST 请求
app.post('/', function (req, res) {
    DUMPDATA = req.body;
    console.log(req.ip);
    res.end('confirm');
    for (var index = 0; index < CLIENTS.length; index++) {
        var socket = CLIENTS[index];
        socket.emit('update', DUMPDATA);
    }
});

// websocket
io.on('connection', function (socket) {
    CLIENTS.push(socket);
    console.log(socket.handshake.address);
    console.log(`a user connected, current users: [${CLIENTS.length}]`);
    socket.on('disconnect', function () {
        for (var index = 0; index < CLIENTS.length; index++) {
            if (CLIENTS[index] === socket) {
                CLIENTS.splice(index, 1);
            }
        }
        console.log(`a user disconnect, current users: [${CLIENTS.length}]`);
    });
});

server.listen(port, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log(`server running at localhost:${port}`);
});
